<?php

namespace App\Api\Three\ShopA;

/**
 * https://docs.qq.com/doc/DRUlEamNJWFFhVmVR
 */

use App\Api\ChannelApi;
use App\Console\Commands\Commission;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

class ChongQingZhongLianTongNwe extends ChannelApi
{
    protected $model;
    protected $appKey = '';
    protected $url = '';
    protected $secret = '';
    protected $channel = '';
    protected $config = [];
    protected $HTTPOK = 1; //检查接口返回的数据 返回1 代表返回正确
    protected $root;
    protected $log;
    protected $isTrue = true;
    protected $return_message = '';
    protected $onLineNum = '';
    protected $source = null;
    protected $pname = null;
    protected $productId = null;
    protected $referrerCode = null;
    protected $getNumProvince = null;
    protected $getNumCity = null;
    protected $msgChannel = null;
    protected $supGetTime;
    protected $contractId;

    public function __construct($url = '', $params = '')
    {
        $this->pname = 'ChongQingZhongLianTongNew';
        $this->log = new Logger('ChongQingZhongLianTongNew');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/ChongQingZhongLianTongNew.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        //必配参数
        $mustParams = array(
            'appCode',
            'HMACMD5',
            'aes',
            'channel',
            // 'product'
        );
        // $params = strToKeyValArr($params);

        $isAll = true;
        $params = strToKeyValArr($params);
        $keys = array_keys($params);
        foreach ($mustParams as $param) {
            if (!in_array($param, $keys)) {
                $isAll = false;
                break;
            }
        }
        if (!$isAll) {
            $this->isTrue = false;
            $this->return_message = '通道配置参数不全';
            return '';
        }
        // $this->source_id = $params['source_id'];
        $this->appKey = $params['appCode'];
        $this->secret = $params['HMACMD5'];
        $this->source = $params['aes'];
        $this->channel = $params['channel'];
        $this->productId = !empty($params['product']) ? $params['product'] : '';
        $this->referrerCode = !empty($params['referrerCode']) ? $params['referrerCode'] : '';
        $this->url = $url;
        $this->model = new ShuZhouLianTongAse($this->appKey, $this->url, $this->secret, $this->source);
        $this->setAddress();
    }

    /**
     * 访问服务商的信息
     *$data 传递过来的数据
     * $method 需要访问的方法
     */
    public function send($data, $method, $aesData = [], $isHeader = true, $noSign = [])
    {
        //构造方法里面不能返回参数只能在调用接口的时候 去返回了
        if ($this->isTrue) {
            $res = $this->model->send($data, $method, $aesData, $isHeader, $noSign);
            // var_dump($res, 11111111111);
            $this->log->info('参数:' . json_encode($data) . '访问的方法:' . $method . '返回结果:' . is_string($res) ? $res : json_encode($res));
            $json_str = str_replace('＼＼', '', $res);

            $out_arr = array();

            preg_match('/{.*}/', $json_str, $out_arr);
            if (!empty($out_arr)) {
                $data = json_decode($res, true);
                if ((isset($data['rspCode']) && $data['rspCode'] == 'M0') || (isset($data['rspCode']) && $data['rspCode'] == '0000') || (isset($data['aCode']) && $data['aCode'] == '0000' && isset($data['bCode']) && $data['bCode'] == '0000')) {
                    return ['code' => 200, 'message' => '访问成功', 'detail' => json_decode($res, true), 'data' => json_decode($res, true)];
                }
                return [
                    'code' => -1,
                    'message' => !empty($data['rspDesc']) ? $data['rspDesc'] : (!empty($data['msg']) ? $data['msg'] : ((!empty($data['aDesc']) && $data['aCode'] != '0000') ? $data['aDesc'] : (!empty($data['bDesc']) ? $data['bDesc'] : '下单失败'))),
                    'detail' => json_decode($res, true), 'data' => json_decode($res, true)
                ];
            }
            return ['code' => -1, 'message' => $res, 'detail' => '', 'data' => []];
        }
        return ['code' => -1, 'message' => $this->return_message, 'detail' => $this->return_message];
    }

    /**
     * 选号查询接口
     * 获取选号，让用户选择号码，同时还有号码搜索功能
     * @param $data
     * @return array
     */
    public function selectNumber($array = array())
    {
        $method = '/link/num/select/v1';
        $address = $this->getAddress($array['numberProvince'], $array['numbercity']);
        // var_dump($address);
        if (empty($address)) {
            return ['code' => -2, 'msg' => '未查询到对应的省市信息'];
        }
        // $goodsId = '';
        // if ($array['channel_code']) {
        //     $params = strToKeyValArr($array['package']);
        //     // $keys = array_keys($params);
        //     if (!empty($params['goodsId'])) {
        //         $goodsId = $params['goodsId'];
        //     }
        // }
        // if (empty($goodsId)) {
        //     return ['status' => -2, 'msg' => '未查询到商品信息'];
        // }
        $data = [
            'goodsId' => $array['channel_code'],
            'provinceCode' => $address->numProvinceCode,
            // 'provinceCode' => 36,
            'cityCode' => $address->numCityCode,
            // 'cityCode' => 370,
            'qryType' => '02',
            'searchCategory' => '2',
            'searchType' => '',
            'searchValue' => !empty($array['searchValue']) ? $array['searchValue'] : '',
            'amounts' => $array['amounts'] ?? 10,
        ];
        // var_dump($data, 111111111);
        $res = $this->send($data, $method);
        // var_dump($res);
        if ($res['code'] != 200) {
            return ['code' => -1, 'msg' => $res['message'], 'data' => []];
        }
        $nums = $res['data'];
        $numbers = [];
        // $i = 0;
        for ($i = 0; $i < count($nums['body']['numArray']) / 12; $i++) {
            $date[] = [
                'iccid' => $nums['body']['numArray'][$i * 12],
                'checkCode' => $array['numbercity'],
                'numberProvince' => $array['numberProvince'],
                'name' => '',
                'chtype' => '',
                'type' => '',
                'province' => $array['numberProvince'],
                'city' => $array['numbercity'],
                'provinceCode' => $address->numProvinceCode,
                'cityCode' => $address->numCityCode
            ];
        }
        if (!$numbers) {
            return ['code' => 200, 'msg' => '加载成功', 'data' => $date];
        }
        //返回失败
        return ['code' => 100, 'msg' => !empty($res['message']) ? $res['message'] : '成功', 'data' => $res];
    }

    /**
     * 身份证信息校验
     * @param $data
     * @return array
     */
    public function checkIdentity($array = array())
    {
        $method = '/link/king/identity/cust/v2';
        $address = $this->getAddress($array['province'], $array['city'], $array['area']);
        if (empty($address)) {
            return ['status' => -2, 'msg' => ''];
        }
        $data = [
            'province' => $address->numProvinceCode,
            'city' => $address->numCityCode,
            'certName' => $array['name'],
            'certNum' => $array['identity'],
        ];
        $res = $this->send($data, $method);
        if ($res['code'] == 1) {

            return ['status' => 1, 'msg' => '成功'];
        }
        return ['status' => -1, 'msg' => !empty($res['message']) ? $res['message'] : '验证失败'];
    }

    public function setAddress()
    {
        switch ($this->channel) {
            case '07-4355-airi-b2gt':
                $this->getNumProvince = '上海';
                $this->getNumCity = '上海';
                $this->msgChannel = 'hebq';
                break;
            case '07-4355-avpv-9999':
                $this->getNumProvince = '浙江';
                $this->getNumCity = '宁波';
                break;
            case '07-4355-aemn-b8qk':
                $this->getNumProvince = '江苏';
                $this->getNumCity = '苏州';
                break;
            case '07-4355-aemn-b9lp':
                $this->getNumProvince = '江苏';
                $this->getNumCity = '常州';
                break;
            case '07-4355-b09l-9999':
                $this->getNumProvince = '浙江';
                $this->getNumCity = '温州';
                break;
            case '07-4355-aq04-9999':
                $this->getNumProvince = '陕西';
                $this->getNumCity = '延安';
                break;
            case '07-4355-b166-9999':
                $this->getNumProvince = '陕西';
                $this->getNumCity = '延安';
                break;
            case '09-2279-b95y-9999';
                $this->getNumProvince = '重庆';
                $this->getNumCity = '重庆';
                $this->contractId = '91056291'; // 合约id
                break;
            case '09-2279-b95q-9999';
                $this->getNumProvince = '重庆';
                $this->getNumCity = '重庆';
                $this->contractId = '91056291'; // 合约id
                break;
            case '09-2279-baco-9999';
                $this->getNumProvince = '重庆';
                $this->getNumCity = '重庆';
                $this->contractId = '91056291'; // 合约id
                break;
        }
        return 1;
    }

    /**
     * 手机验证码
     * 下单前校验用户手机号码是否真实
     * @param $data
     * @return array
     */
    public function sendCaptcha($data = array())
    {
        $method = '/link/king/card/message/send/v2';
        if (empty($data['identity'])) {
            return ['status' => -3, 'msg' => '请填写身份证号'];
        }
        $goodsId = '';
        if ($data['package']) {
            $params = strToKeyValArr($data['params']);
            // $keys = array_keys($params);
            if (!empty($params['channel'])) {
                $goodsId = $params['channel'];
            }
        }
        if (empty($goodsId)) {
            return ['status' => '-4', 'msg' => '请联系管理员'];
        }
        $dataPost = [
            'certId' => strtoupper($data['identity']),
            'contactNum' => $data['contact'],
            'channel' => $goodsId
        ];
        $res = $this->send($dataPost, $method);
        if ($res['code'] == 1) {
            return ['status' => 1, 'msg' => '发送成功'];
        }
        return ['status' => -1, 'msg' => !empty($rrturnRes['message']) ? $rrturnRes['message'] : '发送失败'];
    }

    /**
     * 验证码校验
     * @param $data
     * @return array
     */
    public function captchaCheck($data = array())
    {
        // var_dump($data);die();
        $method = '/link/king/card/message/check/v2';
        if (empty($data['identity'])) {
            return ['status' => -3, 'msg' => '请填写身份证号'];
        }
        $goodsId = '';
        if (!empty($data['package'])) {
            $params = strToKeyValArr($data['package']);
            if (!empty($params['channel'])) {
                $goodsId = $params['channel'];
            }
        }
        if (empty($goodsId)) {
            return ['status' => '-4', 'msg' => '请联系管理员'];
        }
        if (empty($data['captcha'])) {
            return ['status' => '-5', 'msg' => '验证码不能为空'];
        }
        $dataPost = [
            'certId' => strtoupper($data['identity']),
            'contactNum' => $data['contact'],
            'channel' => $goodsId,
            'captcha' => $data['captcha'],
        ];
        $res = $this->send($dataPost, $method);
        if ($res['code'] == 1) {
            return ['status' => 1, 'msg' => '验证成功'];
        }
        return ['status' => -1, 'msg' => !empty($rrturnRes['message']) ? $rrturnRes['message'] : '验证码验证失败'];
    }

    /**
     * 号码校验
     * @param $data
     * @return array
     */
    public function numberCheck($data = array())
    {
        return ['status' => 1, 'msg' => '成功', 'data' => array()];
    }


    //正式同步订单
    public function syncOrder($array = array())
    {
        $method = '/link/king/card/preOrder/ordersync/v2';
        $parovinceCode = '';
        $cityCode = '';
        if (!empty($array['numberProvince']) && !empty($array['numbercity'])) {
            $address = $this->getAddress($array['numberProvince'], $array['numbercity']);
            if (empty($address)) {
                return ['code' => -2, 'msg' => '号码归属地有误 请检查'];
            }
            $array['provinceCode'] = $parovinceCode = $address->numProvinceCode;
            $array['cityCode'] = $cityCode = $address->numCityCode;
        }
        // 号码的归属地的编号
        if (!empty($array['province']) && !empty($array['city'])) {
            $address = $this->getAddress($array['province'], $array['city']);
            if (empty($address)) {
                return ['code' => -2, 'msg' => '号码归属地有误 请检查'];
            }
            $parovinceCode = $address->numProvinceCode;
            $cityCode = $address->numCityCode;
        }
        if (empty($array['number']) && empty($array['iccid'])) {
            // 系统自己匹配
            if (empty($array['numberProvince']) || $array['numbercity']) {
                $array['numberProvince'] = $array['post_province'];
                $array['numbercity'] = $array['post_city'];
            }
            // $address = $this->getAddress($array['numberProvince'], $array['numbercity']);
            $resNumber = $this->selectNumber($array);
            // var_dump($resNumber, 66666666);
            if (empty($resNumber)) {
                return ['code' => -2, 'msg' => '号码归属地有误 请检查'];
            }
            if (empty($resNumber['code']) || $resNumber['code'] != 200 || empty($resNumber['data'][0]['iccid'])) {
                return ['code' => -3, 'msg' => '未查询到号码'];
            }
            $array['number'] = $resNumber['data'][0]['iccid'];
            $array['provinceCode'] = $resNumber['data'][0]['provinceCode'];
            $array['cityCode'] = $resNumber['data'][0]['cityCode'];
        }

        $data = [
            'goodsId' => $array['goodsId'],
            'provinceCode' => !empty($parovinceCode) ? $parovinceCode : $array['provinceCode'],
            'cityCode' => !empty($cityCode) ? $cityCode : $array['cityCode'],
            'phoneNum' => (!empty($array['number']) ? $array['number'] : (!empty($array['iccid']) ? $array['iccid'] : '')),
            'token' => $array['token'],
            'createTime' => !empty($array['createTime']) ? $array['createTime'] : '',
            'isOpenCF' => '0'
        ];
        $res = $this->send($data, $method);
        return $res;
    }

    function orderSubmit($array = array())
    {
        $method = '/link/king/card/preOrder/preOrdersync';
        $time = date('Y-m-d H:i:s');
        $address = $this->getAddress($array['post_province'], $array['post_city'], $array['post_area']);
        if (empty($address)) {
            return ['status' => -2, 'msg' => '未查询到省市区', ['msg' => '未查询到省市区']];
        }

        //生成意向单
        $data = [
            // 'sourceCode' => $this->appKey,
            'createTime' => $time,
            'updateTime' => $time,
            'goodsId' => $array['channel_code'],
            'orderId' => $array['orderno'],
            'certName' => $array['pay_name'],
            'certNo' => $array['pay_identity'],
            'contactNum' => $array['pay_phone'],
            'postProvinceCode' => $address->postProvinceCode,
            'postCityCode' => $address->postCityCode,
            'postDistrictCode' => $address->postDistrictCode,
            'postAddr' => $array['post_province'] . $array['post_city'] . $array['post_area'] . $array['post_address'],
            'channel' => $this->channel,
            'orderTotalFee' => 0,
            'optProduct' => [
                // 'productId'             => $this->productId,
            ],
            'firstMonthFee' => 'A000011V000002',
            // 'referrerCode'          => '7613440296' // 发展人编码
        ];
        if (!empty($this->referrerCode)) {
            $data['referrerCode'] = $this->referrerCode;  // 发展人编码
        }
        if (!empty($this->productId)) {
            $data['optProduct']['productId'] = $this->productId;
        }
        if (!empty($this->contractId)) {
            $data['contractId'] = $this->contractId;
        }
        if (!empty($array['channel_code']) && $array['channel_code'] == '833203012862') {
            $data['pageUrl'] = 'http://47.104.168.226:81/goodsDetail/133';
            $data['resourceId'] = '2263081559554552';
        }
        if (!empty($array['channel_code']) && $array['channel_code'] == '833203013430') {
            $data['pageUrl'] = 'http://47.104.168.226:81/goodsDetail/225';
            $data['resourceId'] = '1863120643623834';
        }
        $data['launchPlatform'] = '抖音APP';
        // $checkData = $this->checkTwo($data, $array);
        // if (empty($checkData['code']) || $checkData['code'] != 200) {
        //     return $checkData;
        // }
        // 获取号码
        if (!empty($array['numberProvince']) && !empty($array['numbercity'])) {
            $address = $this->getAddress($array['numberProvince'], $array['numbercity']);
            if (empty($address)) {
                return ['code' => -2, 'msg' => '号码归属地有误 请检查', ['msg' => '号码归属地有误 请检查']];
            }
            $array['provinceCode'] = $address->numProvinceCode;
            $array['cityCode'] = $address->numCityCode;
        }
        if (empty($array['number']) && empty($array['iccid'])) {
            // 系统自己匹配
            if (empty($array['numberProvince']) || $array['numbercity']) {
                $array['numberProvince'] = $this->getNumProvince;
                $array['numbercity'] = $this->getNumCity;
            }
            // $address = $this->getAddress($array['numberProvince'], $array['numbercity']);
            $resNumber = $this->selectNumber($array);
            // var_dump($resNumber, 66666666);
            if (empty($resNumber)) {
                return ['code' => -2, 'msg' => '号码归属地有误 请检查', ['msg' => '号码归属地有误 请检查']];
            }
            if (empty($resNumber['code']) || $resNumber['code'] != 200 || empty($resNumber['data'][0]['iccid'])) {
                return ['code' => -3, 'msg' => '未查询到号码', ['msg' => '未查询到号码']];
            }
            $array['number'] = $resNumber['data'][0]['iccid'];
            $array['provinceCode'] = $resNumber['data'][0]['provinceCode'];
            $array['cityCode'] = $resNumber['data'][0]['cityCode'];
        }
        // var_dump($data, 5555555);
        $res = $this->send($data, $method); // 意向单提交
        // $res = ['code' => 200, 'data' => ['body' => json_encode(['token' => 11])]];
        // $res = json_decode($res, true);
        // var_dump($res, 11111111111);
        if ($res['code'] == 200 && !empty($res['data']['body'])) {
            $obj = json_decode($res['data']['body'], true);
            //同步订单
            $array['createTime'] = $time;
            $array['token'] = $obj['token'];
            $array['provinceCode'] = $address->numProvinceCode;
            $array['cityCode'] = $address->numCityCode;
            $array['goodsId'] = $data['goodsId'];
            $rrturnRes = $this->syncOrder($array);  // 同步订单
            if ($rrturnRes['code'] == 200) {
                if (!empty($res['data']['body']) && is_string($res['data']['body'])) {
                    $objRet = json_decode($res['data']['body'], true);
                }

                return ['code' => 200, 'msg' => '成功', 'data' => array(
                    'order_id' => !empty($objRet['orderNo']) ? $objRet['orderNo'] : '',
                    'iccid' => !empty($array['iccid']) ? $array['iccid'] : (!empty($array['number']) ? $array['number'] : ''),
                )];
            }
            return ['code' => -1, 'msg' => !empty($rrturnRes['message']) ? $rrturnRes['message'] : '成功', 'data' => $rrturnRes];
        }
        return ['code' => -1, 'msg' => !empty($res['message']) ? $res['message'] : '成功', 'data' => $res];
    }

    function checkTwo($array = array(), $datas = [])
    {
        // 3.21 风控效验
        $methods = '/link/king/risk/check/v1';
        $address = $this->getAddress($datas['post_province'], $datas['post_city']);
        $dataRes = [
            'certId' => $array['certNo'],
            'certName' => $array['certName'],
            'contactPhone' => $array['contactNum'],
            'postProvinceCode' => $array['postProvinceCode'],
            'postCityCode' => $array['postCityCode'],
            'postDistrictCode' => $array['postDistrictCode'],
            'postAddr' => $array['postAddr'],
            'channel' => $array['channel'],
            'provinceCode' => $address->numProvinceCode,
            'cityCode' => $address->numCityCode
        ];
        // var_dump($dataRes, 222222);
        $res = $this->send($dataRes, $methods);
        // var_dump($res);
        if ($res['code'] == 200 && $res['message'] != '风控校验未通过') {

            return ['code' => 200, 'msg' => '成功'];
        }
        return ['code' => 101, 'msg' => !empty($res['message']) ? $res['message'] : '效验不通过'];
    }

    /**
     * 查询订单状态
     * 用来同步上游订单状态
     * @param $data
     * @return array
     */
    public function queryOrderStatus($data = array())
    {
        // var_dump($array, 11111111);
        if (empty($array['iccid'])) {
            $array['iccid'] = $array['sup_orderno'];
        }
        $res = $this->getOrderMessage($array);
        // $res = '{"code":200,"message":null,"data":[{"id":"724496098565218304","cardSvcnum":"15981844179","cardRegion":"A","userTel":"18539456785","province":"\u6cb3\u5357\u7701","city":"\u90d1\u5dde\u5e02","county":"\u91d1\u6c34\u533a","town":null,"address":"\u701a\u6d77@\u4e2d\u5fc31406","outProdId":"4733","payAmount":0,"havecardType":"4","outOrderid":"4972085623424163113","contactsname":"\u5218\u5fd7\u6052","cordertype":null,"useridNum":null,"userName":"\u5218\u5fd7\u6052","createTime":1661844945000,"memberId":"","orderId":"4972085623424163113","sellerId":"13a62da098834bac8d9d0145140a6c86","appid":"","channel":"1654587998768","changeState":"3","changeTime":1661860596000,"lifeTime":null,"wlCompany":"\u4eac\u4e1c\u5feb\u9012","wlOrderid":"JDV008045220392","reUrl":null,"outProdName":"\u79fb\u52a8\u82b1\u5361\u5b9d\u85cf\u72482020-39\u5143\u65e0\u9884\u5b58\u5165\u7f512022\u5e74\u4e8c\u5b63\u5ea6\uff08\u5408\u4f5c\uff092","ageFlag":"1","orderSource":"10","netpro":"1","originalState":null}]}';
        // var_dump($res);
        if (empty($res['data'])) {
            return $this->returnMsg(100, '数据为空');
        }
        if (empty($res['data'][0])) {
            return $this->returnMsg(101, '未查询到数据');
        }
        $statusDatas = [
            0 => '提交中',
            1 => '提交上游',
            // 2 => '拒收单',
            10 => '审核中',
            11 => '待发货',
            20 => '已发货',
            30 => '已签收',
            40 => '已激活',
            50 => '异常单',
            51 => '取消单',
            60 => '失败单'
        ];
        $returnStatusArr = array(
            '31' => '60',
            '3' => '20',
            '0' => '51',
            '6' => '40',
        );
        $orderState = [
            '3' => '已发货',
            '31' => '激活超时',
            '6' => '已激活',
            '0' => '订单关闭',
        ];
        $getData = $res['data'][0];
        $data = [
            'id' => $getData['id'],
            'sup_order' => $getData['orderId'],
            'created_at' => '',
            'order_desc' => $orderState[$getData['changeState']],
            'order_desc_at' => !empty($getData['changeTime']) ? date('Y-m-d H:i:s', $getData['changeTime'] / 1000) : '',
            'order_num' => $getData['orderId'],
            'pagename' => !empty($getData['outProdName']) ? $getData['outProdName'] : '',
            'iccid' => !empty($getData['cardSvcnum']) ? $getData['cardSvcnum'] : '',
            'express_company' => !empty($getData['wlCompany']) ? $getData['wlCompany'] : '',
            'express_number' => !empty($getData['wlOrderid']) ? $getData['wlOrderid'] : '',
            'status' => !empty($returnStatusArr[$getData['changeState']]) ? $returnStatusArr[$getData['changeState']] : '',
            'three_msg' => !empty($getData['describe']) ? $getData['describe'] : '',
        ];
        return $this->returnMsg(200, '查询成功', [$data]);
    }

    /**
     * 手动同步 部分订单状态
     * @param $data 传递订单信息
     * @return array
     */
    public function partOrderStatus($array = array())
    {
        return ['status' => 1, 'msg' => '成功', 'data' => array()];
    }

    /**
     * 修改第三方的 手机号或地址
     * @param $data 传递订单信息
     * @return array
     */
    public function editOrderPhoneOrAdress($array = array())
    {
        return ['status' => 1, 'msg' => '成功', 'data' => array()];
    }

    /**
     * 查询单个订单状态
     * 自动更新查询的是这个方法
     * @param $data
     * @return array
     */
    public function queryOrderOne($array = array())
    {
        // 限制 五分一次
        $time = time();
        $isTrueSuccess = Cache::get('qiaoliaotian_queryOrder');
        if (!empty($isTrueSuccess) && $isTrueSuccess > (time() - 60 * 5)) {
            return ['status' => 1, 'msg' => '不能一直重复请求'];
        }
        Cache::put('qiaoliaotian_queryOrder', $time, Carbon::now()->addMinutes(5));
        $resGetMessage = $this->getOrderMessage();
        // 获取到的信息 查询是否存在
        $msgId = [];
        $insertData = [];
        if (!empty($resGetMessage['status']) && $resGetMessage['status'] == 1) {
            if (!empty($resGetMessage['data']['body'])) {
                foreach ($resGetMessage['data']['body'] as $key => $v) {
                    // 本地的数据
                    $insertData[] = [
                        'order' => $v['order'],
                        'mobile' => $v['mobile'],
                        'state' => $v['state'],
                        'sim' => $v['sim'],
                        'lgtsId' => $v['lgtsId'],
                        'touchApplyId' => $v['touchApplyId'],
                        'cborder' => $v['cborder'],
                    ];
                    $isDel = true;
                    // 这个应该是 记录的数据
                    $isTrue = DB::table('orders')->where(['sup_orderno' => $v['order']])->first();
                    if ($isTrue && empty($isTrue->iccid)) {
                        $isTrueEdit = DB::table('orders')->where(['sup_orderno' => $v['order']])->update(['iccid' => $v['mobile']]);
                        if (!$isTrueEdit) {
                            $isDel = false;
                        }
                    }
                    if (!empty($v['id']) && $isDel) {
                        $msgId[] = $v['id'];
                    }
                    if (count($insertData) >= 50) {
                        DB::table('liantong_push_log')->insert($insertData);
                        $insertData = [];
                    }
                }
            }
        }
        if (!empty($msgId)) {
            // 删除消息
            $this->deleteOrderStatus(['msgId' => $msgId]);
        }
        // 然后更新
        // 然后删除订单的信息
        $resDelMessage = $this->deleteOrderStatus();
        return ['status' => 1, 'msg' => '成功', 'data' => $resGetMessage];
    }

    /**
     * 订单消息的获取
     */
    public function getOrderMessage($order = array())
    {
        $method = '/link/king/card/msg/get/v1';
        $data = [
            'msgChannel' => !empty($this->msgChannel) ? $this->msgChannel : 'hebq',
            'type' => 4,
        ];
        // var_dump($data, 44444444444);
        $res = $this->send($data, $method);

        $this->log->info('订单状态---' . json_encode($res));
        if (!empty($res['status']) && $res['status'] == 1) {

            return ['status' => 1, 'msg' => $res['message'], 'data' => $res['data']];
        }
        return ['status' => -1, 'msg' => !empty($res['message']) ? $res['message'] : '', 'data' => []];
    }

    /**
     * 删除订单状态
     * 用来删除上游订单状态
     * @param $data
     * @return array
     */
    public function deleteOrderStatus($data = array())
    {
        // var_dump($data);
        $method = '/link/king/card/msg/del/v1';
        $msgId = '';
        if (!empty($data['msgId']) && is_array($data['msgId'])) {
            $msgId = implode(',', $data['msgId']);
        }
        if (empty($msgId)) {
            return $this->returnMsg(100, '未查询到消息id');
        }
        $data = [
            'msgId' => $msgId,
            'type' => 4,
        ];
        // var_dump($data, 44444444444);
        // return true;
        $res = $this->send($data, $method);
        $this->log->info('订单消息删除---' . json_encode($res));
        if (!empty($res['status']) && $res['status'] == 1) {
            // 将更新的信息存入数据库 以防误删
            return ['status' => 1, 'msg' => $res['message'], 'data' => $res['data']];
        }
        return ['status' => -1, 'msg' => !empty($res['message']) ? $res['message'] : '', 'data' => []];
    }

    /**
     * 号码库同步
     * 同步号码接口，返回固定时间戳之后的号码变动，同步到本地号码库
     * @param $data
     * @return array
     */
    public function numberAsync($data = array())
    {
        return ['status' => 1, 'msg' => '成功'];
    }

    /**
     * 地址信息查询
     * @param $data
     * @return array
     */
    public function addressQuery($data = array())
    {
        return ['status' => 1, 'msg' => '成功', 'data' => array()];
    }

    public function getAddress($province, $city, $district = '')
    {
        // $where = [
        //     'postProvinceName' => $province,
        //     'postCityName' =>$city,

        // ];
        // if(!empty($district)){
        //     $where['postDistrictName'] =  $district;
        // }
        $province = str_replace('市', '', $province);
        $province = str_replace('省', '', $province);
        $city = str_replace('市', '', $city);
        $where = [
            ['postProvinceName', 'like', $province . '%'],
            ['postCityName', 'like', $city . '%']
        ];
        if (!empty($district)) {
            $district = str_replace('市', '', $district);
            $district = str_replace('区', '', $district);
            $where[] = ['postDistrictName', 'like', $district . '%'];
        }
        // var_dump($where);
        // $where = [
        //     'numProvinceCode' => 36,
        //     'numCityCode' => 370
        // ];
        // var_dump($where, 1111111111);
        $res = DB::table('shlt_address_code')->where($where)->first();
        // var_dump($res, 22222222222);
        return $res;
    }

    public function getAsyncAddress()
    {
        $method = '/link/king/postInfo/qry';
        $data = [
            'provinceCode' => 76
        ];
        $res = $this->send($data, $method);
        // var_dump($res);die();
        if ($res['code'] == 1) {
            DB::table('flow_lt_address_code')->delete();
            DB::table('flow_lt_address_code')->insert($res['data']['body']);
        }

        return ['status' => -1, 'msg' => !empty($res['message']) ? $res['message'] : ''];
    }

    public function address($data)
    {
        return [
            76 => '河南'
        ];
    }
}
